package com.zhong.wechat.handler;

import com.zhong.wechat.enums.WeChatMessageTypeEnum;
import com.zhong.wechat.untils.RedisUntil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ReceiveTextMsgHandler implements WeChatMegHandler {

    private static final String KEY_WORLD = "验证码";

    private static final String LOGIN_PREFIX = "login_code";
    @Resource
    private RedisUntil redisUntil;

    @Override
    public WeChatMessageTypeEnum getMsgType() {
        return WeChatMessageTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> msgMap) {
        //用户发的信息
        String content = msgMap.get("Content");
        if (!KEY_WORLD.equals(content)) {
            return null;
        }
        //接收者
        String toUserName = msgMap.get("ToUserName");
        //发送者
        String fromUserName = msgMap.get("FromUserName");
        log.info("接收到用户: {} 消息: {}", fromUserName, content);
        int number = ThreadLocalRandom.current().nextInt(100000, 1000000);
        //将验证码存入缓存中
        String numKey = redisUntil.buildKey(LOGIN_PREFIX,Integer.toString(number));
        redisUntil.setNx(numKey,fromUserName,5L, TimeUnit.MINUTES);
        String replyMsg = "您当前的验码是：" + number + "五分钟内有效！！！";
        return """
                <xml>
                  <ToUserName><![CDATA[${toUser}]]></ToUserName>
                  <FromUserName><![CDATA[${fromUser}]]></FromUserName>
                  <CreateTime>12345678</CreateTime>
                  <MsgType><![CDATA[text]]></MsgType>
                  <Content><![CDATA[${replyMsg}]]></Content>
                </xml>
                """.replace("${toUser}", fromUserName).replace("${fromUser}", toUserName).replace("${replyMsg}", replyMsg);

    }
}
